package com.chenfan.ccp.plug.mq.util;

import com.chenfan.ccp.util.start.ApplicationContextUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Method;

public class MqTemplate {
    private static final Logger logger = LoggerFactory.getLogger("mqTemplate");
    private static final String rocketMqSendSuccess = "SEND_OK";
    private static final String rocketMQTemplateName = "rocketMQTemplate";
    private static final String syncSendName = "syncSend";
    private static final String sendStatusName = "sendStatus";

    private MqTemplate() {
    }

    public static boolean sendMsg(String topic, String msg) {
        return tryRocketMqTemplate(topic, msg);
    }

    private static boolean tryRocketMqTemplate(String topic, String msg) {
        try {
            Object rocketMQTemplate = ApplicationContextUtil.getContext().getBean(rocketMQTemplateName);

            if (rocketMQTemplate != null) {
                Class<?> aClass = Class.forName("org.springframework.messaging.Message");
                Class<?> aClass1 = Class.forName("org.springframework.messaging.support.MessageBuilder");
                Method withPayload = aClass1.getDeclaredMethod("withPayload", Object.class);
                Object invoke1 = withPayload.invoke(null, msg);
                Object build = invoke1.getClass().getMethod("build").invoke(invoke1);
                Method syncSend = rocketMQTemplate.getClass().getMethod(syncSendName, String.class, aClass);
                Object invoke = syncSend.invoke(rocketMQTemplate, topic, build);
                if (invoke != null) {
                        return true;
                }

            }
        } catch (Throwable e) {
            logger.info("mq load fail!!");
        }


        return false;
    }
}
